﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Diagnostics;
using System.Drawing.Printing;
using TireBias.Models;
using CrystalDecisions.CrystalReports.Engine;
using iTextSharp.text.html.simpleparser;
using System.Text;
using System.Data;
using WinNemoLib;

namespace TireBias.Controllers
{
    public class PRINT_PDFController : Controller
    {
        public class PdfResult : ActionResult
        {
            List<TailModel.PlyRoll_DS> _Input;
     
            string pth;
            string _Ply;
            Stream crBarcode;
            PdfContentByte _pcb;

            private static readonly BaseFont font = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252,false);
            BaseFont THCodefont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\CORDIA.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            BaseFont EnCodefont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\tahoma.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            //
            // GET: /PRINT_PDF/
            public PdfResult(List<TailModel.PlyRoll_DS> data,string ptha,string ply,Stream io = null)
            {
                _Input = data;          
                pth = ptha;
                _Ply = ply;
                crBarcode = io;
            }
            private void PrintText(string text, int x, int y)
            {
                _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
            }


            public override void ExecuteResult(ControllerContext context)
            {
                
                try
                {                   
                    var response = context.HttpContext.Response;
                    response.ContentType = "application/pdf";

                    //Document doc = new Document(PageSize.A4_LANDSCAPE.Rotate());
                
                    //PdfReader reader = new PdfReader(pth);                 
                    PdfReader reader = new PdfReader(crBarcode);                 
                  
                    Rectangle psize = reader.GetPageSizeWithRotation(1);
                    Document doc = new Document(psize);
                    PdfWriter writer = PdfWriter.GetInstance(doc, response.OutputStream);
                    PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
                    //string lotnum = _Input[0]._plylot;
                    //string code = _Input[0]._topcode + '+' /*0*/
                    //    + _Ply + '+'  /*1*/
                    //    + _Input[0]._sizes  /*2*/
                    //    + '+' + _Input[0]._forming  /*3*/
                    //    + '+' + lotnum + '+'  /*4*/
                    //    + _Input[0]._plyexp + '+'  /*5*/
                    //    + _Input[0]._plylen + '+'  /*6*/
                    //    + _Input[0]._rollno + '+' /*7*/
                    //    + _Input[0]._biasno + '+'  /*8*/
                    //    + _Input[0]._plandt + '-'  /*9*/
                    //    + _Input[0]._itemno + '-'  /*10*/
                    //    + _Input[0]._sitemno; /*11*/

                    //Image image = iTextSharp.text.Image.GetInstance(QRCodeHtmlHelper.enCode_barcode(code, 5, 5));
                    //image.ScaleToFit(50, 50);

                    //writer.AddJavaScript("this.print(true);",false );
                    writer.SetOpenAction(action);

                    doc.Open();
                    PdfTemplate page = writer.GetImportedPage(reader, 1);
                    
                    int rotation;
                    doc.SetPageSize(reader.GetPageSizeWithRotation(1)); 
                    doc.NewPage();
                    rotation = reader.GetPageRotation(1);
                    _pcb = writer.DirectContent;

                             
                    ////add barcode 2
                    //image.SetAbsolutePosition(30, 50);
                    //doc.Add(image);
                    ////add barcode 3
                    //image.SetAbsolutePosition(730, 220);
                    //doc.Add(image);

                     //landscape mode    
                    if (rotation == 90 || rotation == 270)
                    {
                        _pcb.AddTemplate(page, 0, -1f, 1f, 0, 0,
                        reader.GetPageSizeWithRotation(1).Height);
                    }

                    //portrait mode
                    else
                    {
                        _pcb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }

              
                    _pcb.BeginText();
                    
                    _pcb.SetFontAndSize(font, 70);
                    
                    _pcb.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
                    //  #########  ข้อมูล Topping #############
                    //PrintText(_Input[0]._topcode.Replace("-",""), 325, 475);
                    //PrintText(_Input[0]._cartno, 715, 475);

                    //_pcb.SetFontAndSize(font, 55);
                    //PrintText(_Input[0]._side, 28, 360);
                    //PrintText(_Input[0]._sizes, 140, 360);
                    //PrintText(_Input[0]._forming, 680, 360);

                    //_pcb.SetFontAndSize(font, 24);

                    //PrintText(_Input[0]._topLot, 112, 490);//ล็อต
                    //PrintText(_Input[0]._toproll, 280, 490);//ม้วนที่

                    //PrintText(_Input[0]._angel, 180, 290);//องศา
                    //PrintText(_Input[0]._Plymin, 180, 235);//width

                    //_pcb.SetFontAndSize(font, 36);
                    //PrintText(_Input[0]._plylen, 490, 290);//ความกว้างผลิตจริง

                    //_pcb.SetFontAndSize(font, 14);
                    ////LotNumber
               
                    //PrintText(lotnum.Substring(0,2), 295, 170);
                    //PrintText(lotnum.Substring(3, 2), 365, 170);
                    //PrintText(lotnum.Substring(6, 1), 445, 170);
                    ////Biasno
                    //PrintText( _Input[0]._biasno, 583, 170);

                    ////Expire
                    //string exp = _Input[0]._plyexp;
                    //PrintText(exp.Substring(0, 2), 295, 135);
                    //PrintText(exp.Substring(3, 2), 365, 135);
                    //PrintText(exp.Substring(6,4), 436, 135);

                    ////cartno
                    //PrintText( _Input[0]._rollno, 520, 170);
                    ////empname
                    ////_pcb.SetFontAndSize(THCodefont, 16);
                    //PrintText(_Input[0]._empname, 650, 135);

                    _pcb.EndText();
                    writer.Flush();
                    HTMLWorker htmlWorker = new HTMLWorker(doc);

      
                    //image.SetAbsolutePosition(30, 500);
                    //doc.Add(image);
                    
                
                    //doc.Add(image);


                    doc.Close();
                }
                catch (Exception ex)
                {
                    WinNemoLib.Nemo.Error(ex);
                }

            }

            public void Print_PLY(Document doc)
            {
                Font Nfont = new Font(THCodefont, 45, Font.BOLD);
                Font Bfont = new Font(EnCodefont, 50, Font.BOLD);
                Font Hfont = new Font(THCodefont, 55, Font.BOLD);

                doc.SetMargins(0,0,0,0);
      
                Image image = iTextSharp.text.Image.GetInstance(QRCodeHtmlHelper.enCode_barcode("HN-43MH+121204R011+500+INOACINTERNATIONAL+2013-05-09+001", 5, 5));
                image.ScaleToFit(70, 70);

                image.SetAbsolutePosition(10, 520);
                doc.Add(image);

                PdfPTable tableT = new PdfPTable(4);
                float[] widths = new float[] { 3f, 2f, 2f,1f };
                tableT.DefaultCell.Border = 0;
                tableT.SetWidths(widths);
                tableT.DefaultCell.HorizontalAlignment = 1;
                tableT.AddCell("");
               
                PdfPCell tem = new PdfPCell(new Phrase("ชนิดผ้าใบ", Nfont));
                tem.Border = 0;
                tem.MinimumHeight = 100f;
                tem.HorizontalAlignment = 1;
                tableT.AddCell(tem);
                tableT.AddCell(new Phrase("HN-43MH", Hfont));

                PdfPCell TblCell = new PdfPCell(new Phrase(" ", Hfont));              
                tableT.AddCell(TblCell);

                doc.Add(tableT);
            }

        }

        public Stream ExportPDF()
        {
            ReportClass report = new ReportClass();
            report.FileName = Server.MapPath(@"~\Report\Demoreport.rpt");
            report.Load();

            Stream stream = report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            return stream;
        }

        public Stream ExportPDF_BARCODE(string biasno, string plandt, string itemno, string sitemno, string side, string rows,DataTable dt1)
        {

            try
            {
                dt1.Columns.Add(new DataColumn("Barcode", typeof(System.Byte[])));

                string code = dt1.Rows[0]["topcrdcd"].ToString() + '+' /*0*/
                            + side + '+'  /*1*/
                            + dt1.Rows[0]["sizes"].ToString()  /*2*/
                            + '+' + dt1.Rows[0]["forming"].ToString()   /*3*/
                            + '+' + dt1.Rows[0]["plylot"].ToString() + '+'  /*4*/
                            + DateUtil.ToDisplayDate(dt1.Rows[0]["plyexp"], DateUtil.eLanguage.EN) + '+'  /*5*/
                            + dt1.Rows[0]["plylen"].ToString() + '+'  /*6*/
                            + dt1.Rows[0]["rollno"].ToString() + '+' /*7*/
                            + dt1.Rows[0]["biasno"].ToString() + '+'  /*8*/
                            + DateUtil.ToDisplayDate(dt1.Rows[0]["plandt"], DateUtil.eLanguage.EN) + '-'  /*9*/
                            + dt1.Rows[0]["itemno"].ToString() + '-'  /*10*/
                            + dt1.Rows[0]["sitemno"].ToString(); /*11*/

                dt1.Rows[0]["Barcode"] = QRCodeHtmlHelper.enCode_barcode(code, 5, 5);
                //dt1.Rows[0]["topsheet"] = 1;
                //dt1.Rows[0]["tapesheet"] = 1;
                dt1.TableName = "DataTable1";
                ReportClass report = new ReportClass();
                ReportDocument rp = new ReportDocument();

                rp.FileName = Server.MapPath(@"~\Report\crBarcode.rpt");
                rp.Load(rp.FileName);
                rp.SetDataSource(dt1);
                Stream stream = rp.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
                return stream;
            }
            catch (Exception ex)
            {
                WinNemoLib.Nemo.Error(ex);
                throw;
            }

        }

        //public Stream ExportPDF_GEN_BARCODE(string biasno, string plandt, string itemno, string sitemno, string side, string rows, DataTable dt1)
        //{

        //    try
        //    {  
        //        dt1.Columns.Add(new DataColumn("qrcode", typeof(System.Byte[])));
        //        foreach (DataRow dr in dt1.Rows)
        //        {
        //            dr["qrcode"] = QRCodeHtmlHelper.enCode_barcode(dr["text"].ToString(), 5, 5);      
        //        }
        //        dt1.TableName = "qrcode";
        //        ReportClass report = new ReportClass();
        //        ReportDocument rp = new ReportDocument();

        //        rp.FileName = Server.MapPath(@"~\Report\gendata.rpt");
        //        rp.Load(rp.FileName);
        //        rp.SetDataSource(dt1);
        //        Stream stream = rp.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        //        return stream;
        //    }
        //    catch (Exception ex)
        //    {
        //        WinNemoLib.Nemo.Error(ex);
        //        throw;
        //    }

        //}

        public ActionResult PRINT_PDF_BARCODE(string biasno, string plandt, string itemno, string sitemno, string side,string rows)
        {
            List<TailModel.PlyRoll_DS> list = new List<TailModel.PlyRoll_DS>();
            TailModel md = new TailModel();

            //list = md.PRINT_PLY(biasno, plandt, itemno, sitemno, side, rows);



            string report = Server.MapPath(@"~\Report\Tamp12.pdf");
            
            DataTable dt1 = md.PRINT_PLY_DT(biasno, plandt, itemno, sitemno, side, rows);

             Stream reader = this.ExportPDF_BARCODE(biasno, plandt, itemno, sitemno, side, rows,dt1);
            return new PdfResult(list, report, side,reader);


          
//            return File(this.ExportPDF_BARCODE(biasno, plandt,  itemno,sitemno,side,  rows), "application/pdf");
        }



        public ActionResult PRINT_PDF_MATTOMAT(string biasno, string plandt, string itemno, string sitemno, string _rollno, string side)
        {
            List<TailModel.PlyRoll_DS> list = new List<TailModel.PlyRoll_DS>();
            ReportModel md = new ReportModel();

            DataTable dt = md.SEL_MATCHANGE(biasno,plandt,itemno,sitemno,_rollno,side);

            Stream reader = this.ExportPDF_BARCODE(biasno, plandt, itemno, sitemno,side, _rollno, dt);
            return new PdfResult(list, "", side, reader);

        }




    }
}
